<template>
  <div class="app-container">
    <el-tabs v-model="activityType" @tab-click="handleClick">
      <el-tab-pane
        v-for="item in allTabs"
        :key="item.id"
        :label="item.menuName"
        :name="item.id"
        @click="() => console.log('点击了标签页', item.id)"
      ></el-tab-pane>
    </el-tabs>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="主题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入主题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="currentStatus">
        <el-select
          v-model="queryParams.currentStatus"
          placeholder="全部状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in statusList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="我的">
        <el-switch v-model="queryParams.isMy" @change="handleQuery">
        </el-switch>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="tableData">
      <el-table-column prop="title" label="主题" show-overflow-tooltip></el-table-column>
      <el-table-column prop="sort" label="排序" align="center"></el-table-column>
      <el-table-column label="WAP端封面" align="center">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.wapImgUrl"
            style="width: 80px; height: 80px"
            :src="baseUrl + scope.row.wapImgUrl"
            fit="cover"
            :preview-src-list="[baseUrl + scope.row.wapImgUrl]"
          >
            <div slot="error" class="image-slot" style="width: 80px; height: 80px; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #999;">
              暂无图片
            </div>
          </el-image>
          <span v-else style="color: #999;">暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="PC端封面" align="center">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.pcImgUrl"
            style="width: 80px; height: 80px"
            :src="baseUrl + scope.row.pcImgUrl"
            fit="cover"
            :preview-src-list="[baseUrl + scope.row.pcImgUrl]"
          >
            <div slot="error" class="image-slot" style="width: 80px; height: 80px; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #999;">
              暂无图片
            </div>
          </el-image>
          <span v-else style="color: #999;">暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="视频上传" align="center">
        <template slot-scope="scope">
          <el-link
            v-if="scope.row.fileUrl"
            :href="baseUrl + scope.row.fileUrl"
            target="_blank"
            type="primary"
            :underline="false"
          >
            {{ baseUrl + scope.row.fileUrl }}
          </el-link>
          <span v-else style="color: #999;">暂无视频</span>
        </template>
      </el-table-column>
      <el-table-column label="内容介绍" prop="contentIntroduce" show-overflow-tooltip>
        <template slot-scope="scope">
          <div v-html="scope.row.contentIntroduce" style="max-height: 60px; overflow: hidden;"></div>
        </template>
      </el-table-column>
      <el-table-column prop="currentStatus" label="审核状态">
        <template v-slot="scope">
          {{ formatCurrStatus(scope.row.currentStatus) }}
        </template>
      </el-table-column>
      <el-table-column prop="currentStatus" label="发布状态">
        <template v-slot="scope">
          {{ formatPublishStatus(scope.row.currentStatus) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right">
        <template slot-scope="scope">
          <Actions
            :isAudit="true"
            :row="scope.row"
            :currName="currName"
            @onPublish="onPublish"
            @onOffShelf="onOffShelf"
            @onDetail="onDetail"
            @onAudit="handleSubit"
          />
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      title="详情"
      :visible.sync="visibleDetail"
      width="70%"
      :destroy-on-close="true"
    >
      <Detail
        ref="Detail"
        :activityType="activityType"
        @cancel="onCancelDetail"
      />
    </el-dialog>
    <!-- 审核提交弹窗 -->
    <el-dialog
      :title="title2"
      :visible.sync="open2"
      width="800px"
      append-to-body
    >
      <el-form ref="form" :model="form2" :rules="rules2" label-width="100px">
        <template>
          <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
            <el-tab-pane label="默认" name="first">
              <el-form-item v-if="!isBackout" label="审批结果" prop="isAgree">
                <el-radio
                  @input="isAgreeInput"
                  v-model="form2.isAgree"
                  label="1"
                  >同意</el-radio
                >
                <el-radio
                  @input="isAgreeInput"
                  v-model="form2.isAgree"
                  label="2"
                  >不同意</el-radio
                >
              </el-form-item>

              <el-form-item
                v-if="form2.isAgree == '2'"
                label="回退节点"
                prop="previousNode"
              >
                <el-select
                  @change="previousNodeChange"
                  v-model="form2.previousNode"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in previousNodeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item
                v-if="canShowEmpSelect"
                label="审批人员"
                prop="nextEmp"
              >
                <el-select
                  v-model="form2.nextEmp"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in nextEmpList"
                    :key="item.userId"
                    :label="item.userId + '-' + item.userCnName"
                    :value="item.userId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="审批意见" prop="actionNote">
                <el-input type="textarea" v-model="form2.actionNote"></el-input>
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="checkSubmit" type="primary">提交</el-button>
        <el-button @click="homeDetail" type="warning">预览</el-button>
        <el-button @click="open2 = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  checklist,
  publish,
  offShelf,
  listUsers,
  checkSubmit,
} from "@/api/activityConfiguration";
import { getLoginName } from "@/utils/auth";
import { getUserInfo } from "@/api/login";
import { getMenuTree, getListByParentId } from "@/api/activityMenu";
import Detail from "./detail.vue";
import { formatCurrStatus, formatPublishStatus } from "./status";
import Actions from "./actions.vue";
export default {
  components: {
    Detail,
    Actions,
  },
  data() {
    return {
      formatCurrStatus,
      formatPublishStatus,
      showSearch: true,
      queryParams: {
        title: "",
        isMy: true,
        menuId: null, // 初始值设为 null，将在获取菜单数据后设置为第一个菜单的ID
      },
      baseUrl: process.env.VUE_APP_BASE_API,
      pageParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      // 添加活动菜单列表和缓存
      activityMenuList: [],
      activityMenuCache: {},
      currName: "",
      statusList: [
        {
          id: "1",
          name: "草稿",
        },
        {
          id: "2",
          name: "待一级审核",
        },
        {
          id: "3",
          name: "待二级审核",
        },
        {
          id: "4",
          name: "待发布",
        },
        {
          id: "5",
          name: "已发布",
        },
      ],
      statusRoleDict: {
        2: "reviewer_l1",
        3: "reviewer_l2",
        4: "publisher",
      },
      loading: false,
      tableData: [],
      visible: false,
      dialogTitle: "",
      visibleDetail: false,
      activityType: null, // 初始值设为 null，将在获取菜单数据后设置为第一个菜单的ID

      open2: false,
      title2: "",
      form2: {
        id: null,
        // 审批节点
        nextEmp: null,
        // 上一个节点
        previousNode: "",
        // 同意/不同意
        isAgree: "1",
        // 审批意见
        actionNote: "",
        // 当前状态
        currentStatus: null,
      },
      rules2: {},
      activeName: "first",
      isBackout: false,
      nextEmpList: [],
      previousNodeList: [],
      menuList: [],
    };
  },
  async created() {
    this.currName = getLoginName();
    // 先获取菜单数据
    await this.getMenuData();
    // 确保初始的activityType与初始选中标签页的ID一致，并且转换为字符串
    // 如果菜单列表已加载，使用第一个菜单的ID；否则使用当前 menuId
    if (this.menuList && this.menuList.length > 0) {
      const firstMenuId = String(this.menuList[0].id);
      this.activityType = firstMenuId;
      this.queryParams.menuId = firstMenuId;
    } else if (this.queryParams.menuId) {
      this.activityType = String(this.queryParams.menuId);
    } else {
      // 如果没有数据，使用默认值
      this.activityType = "1";
      this.queryParams.menuId = null;
    }
    
    // 如果初始标签页不是互动体验，加载对应的活动类型列表
    if (this.activityType !== "1") {
      this.loadActivityMenus(this.activityType);
    }
    
    this.getPage();
  },
  computed: {
    allTabs() {
      // 合并固定标签和动态菜单标签
      return this.menuList;
    },
    canShowEmpSelect() {
      // 如果当前状态是待发布，不同意，且回退节点不是草稿
      if (this.form2.currentStatus == "4") {
        if (this.form2.isAgree == "2" && this.form2.previousNode != "1") {
          return true;
        }
      } else {
        if (this.form2.isAgree == "1") {
          return true;
        } else {
          if (this.form2.previousNode != "1") {
            return true;
          }
        }
      }
      return false;
    },
  },
  methods: {
    getPage() {
      // 确保menuId有值，如果没有则使用第一个菜单的ID
      let menuId = this.queryParams.menuId;
      if (!menuId && this.menuList && this.menuList.length > 0) {
        menuId = String(this.menuList[0].id);
        this.queryParams.menuId = menuId;
      } else if (!menuId) {
        menuId = "1"; // 兜底值
      }
      
      // 根据当前选中的标签页ID判断activityType
      // 如果是互动体验(id=1)，则activityType=1，否则activityType=2
      const realActivityType = menuId === "1" ? "1" : "2";
      
      const params = {
        pageNum: this.pageParams.pageNum,
        pageSize: this.pageParams.pageSize,
        activityType: realActivityType,
        menuId: String(menuId),
        ...this.queryParams,
      };
      
      // 避免重复发送menuId，因为它已经被单独设置了
      delete params.menuId;
      
      // 将处理后的menuId添加回params
      params.menuId = String(menuId);
      
      this.loading = true;
      checklist(params).then((res) => {
        this.tableData = res.data.records;
        this.loading = false;
      });
    },
    getMenuData() {
      return new Promise((resolve) => {
        getMenuTree(1).then((res) => {
          if (res.code === 200 && res.data) {
            // Ensure all ids are strings
            this.menuList = res.data.map(item => ({
              ...item,
              id: String(item.id) // Convert id to string
            }));
            
            // 设置默认选中第一个tab（使用返回数据的第一个菜单ID）
            if (this.menuList && this.menuList.length > 0) {
              const firstMenuId = String(this.menuList[0].id);
              this.queryParams.menuId = firstMenuId;
            }
          } else {
            // 如果没有数据，使用默认值
            this.queryParams.menuId = "1";
          }
          resolve();
        }).catch((error) => {
          console.error("获取菜单数据失败:", error);
          // 即使获取菜单失败，也设置默认值
          this.queryParams.menuId = "1";
          resolve();
        });
      });
    },
    handleQuery() {
      this.getPage();
    },
    resetQuery() {
      // 重置查询条件，但保留当前的menuId
      const currentMenuId = this.queryParams.menuId || (this.menuList && this.menuList.length > 0 ? String(this.menuList[0].id) : "1");
      this.queryParams.title = "";
      this.queryParams.publishStatus = null;
      // 重置状态查询条件
      this.queryParams.currentStatus = null;
      // 确保保留当前的menuId
      this.queryParams.menuId = currentMenuId;
      this.getPage();
    },
    onPublish(id) {
      this.$confirm("你确认要发布活动内容吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        publish(id).then(() => {
          this.getPage();
        });
      });
    },
    onOffShelf(id) {
      this.$confirm("你确认要下架活动内容吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        offShelf(id).then(() => {
          this.getPage();
        });
      });
    },
    onDetail(id) {
      this.visibleDetail = true;
      this.$nextTick(() => {
        // 根据当前选中的标签页ID判断activityType
        const realActivityType = this.queryParams.menuId === "1" ? "1" : this.queryParams.menuId;
        
        // 更新activityType只用于传递给Detail组件
        this.$refs["Detail"].onDetail(id, realActivityType);
      });
    },
    handleClick(tab) {
      // 确保将tab.name转换为字符串类型
      const tabId = String(tab.name);
      
      console.log('切换标签页，tabId:', tabId, 'tab对象:', tab);
      
      // 设置activityType和menuId
      this.activityType = tabId;
      this.queryParams.menuId = tabId;
      
      // 清除缓存，强制重新加载
      if (tabId !== "1") {
        delete this.activityMenuCache[tabId];
        this.loadActivityMenus(tabId);
      }
      
      // 重置查询条件
      this.queryParams.title = "";
      this.queryParams.publishStatus = null;
      this.queryParams.currentStatus = null;
      
      // 重新获取数据
      this.getPage();
    },
    
    // 备用版本的handleClick，以防原版本不起作用
    tabClickHandler(tab) {
      // 确保将tab.name转换为字符串类型
      const tabId = String(tab.name);
      
      console.log('备用-切换标签页，tabId:', tabId);
      
      // 设置activityType和menuId
      this.activityType = tabId;
      this.queryParams.menuId = tabId;
      
      // 清除缓存，强制重新加载
      if (tabId !== "1") {
        delete this.activityMenuCache[tabId];
        console.log('备用-清除缓存并开始加载活动类型列表');
        // 直接调用API获取数据
        this.loadActivityMenus(tabId);
      }
      
      // 重置查询条件
      this.queryParams.title = "";
      this.queryParams.publishStatus = null;
      this.queryParams.currentStatus = null;
      
      // 重新获取数据
      this.getPage();
    },
    // 同意不同意事件
    async isAgreeInput() {
      // 回退节点清空
      this.form2.previousNode = "";
      this.previousNodeList = [];

      // 下一个选择人员也清空
      this.form2.nextEmp = "";
      this.form2.nextEmpList = [];

      // 不同意
      if (this.form2.isAgree == "2") {
        if (
          this.form2.currentStatus == "4" ||
          this.form2.currentStatus == "5"
        ) {
          this.previousNodeList = [
            {
              value: "1",
              label: "草稿",
            },
            {
              value: "2",
              label: "一级审核",
            },
            {
              value: "3",
              label: "二级审核",
            },
          ];
        } else if (this.form2.currentStatus == "3") {
          this.previousNodeList = [
            {
              value: "1",
              label: "草稿",
            },
            {
              value: "2",
              label: "一级审核",
            },
          ];
        } else if (this.form2.currentStatus == "2") {
          this.previousNodeList = [
            {
              value: "1",
              label: "草稿",
            },
          ];
        }
      } else {
        // 如果是一级审核员，那么弹出的二级审核员列表；如果是二级审核员，那么弹出的发布者列表；如果是发布者，那么没有审核按钮，只有发布按钮
        if (this.form2.currentStatus != "4") {
          let res = await listUsers(
            "kb",
            this.statusRoleDict[parseInt(this.form2.currentStatus) + 1 + ""]
          );
          if (res.code == 200) {
            this.nextEmpList = res.data;
          }
        }
      }
    },
    async previousNodeChange() {
      // 清空数据
      this.form2.nextEmp = "";
      this.nextEmpList = [];

      if (this.form2.previousNode == "1") {
        return;
      }

      let res = await listUsers(
        "kb",
        this.statusRoleDict[this.form2.previousNode]
      );
      if (res.code == 200) {
        this.nextEmpList = res.data;
      }
    },
    // 提交弹窗
    async handleSubit(row) {
      this.form2.id = row.id;

      this.form2.previousNode = "";
      this.previousNodeList = [];

      this.form2.nextEmp = null;
      this.nextEmpList = [];

      this.form2.actionNote = "";

      // 当前状态 1：草稿 2：待一级审核 3：待二级审核 4：待发布 5：已发布
      this.form2.currentStatus = row.currentStatus;

      // 撤销
      if (row.currentStatus == "5") {
        this.isBackout = true;
        this.title2 = "撤回";
        this.form2.isAgree = "2";

        this.isAgreeInput();
      }
      // 审核
      else {
        this.isBackout = false;
        this.title2 = "审核";
        this.form2.isAgree = "1";
        // 如果是一级审核员，那么弹出的二级审核员列表；如果是二级审核员，那么弹出的发布者列表；如果是发布者，那么没有审核按钮，只有发布按钮
        if (this.form2.currentStatus != "4") {
          let res = await listUsers(
            "kb",
            this.statusRoleDict[parseInt(this.form2.currentStatus) + 1 + ""]
          );
          if (res.code == 200) {
            this.nextEmpList = res.data;
          }
        }
      }
      this.open2 = true;
    },
    onCancelDetail() {
      this.visibleDetail = false;
    },
    async homeDetail() {
      // 根据当前选中的标签页ID判断activityType
      // 如果是互动体验(id=1)，则activityType=1，否则activityType=2
      const realActivityType = this.queryParams.menuId === "1" ? "1" : "2";
      if (realActivityType == "1") {
        window.open(
          "https://worldskillsmuseum.cn/#/active/detail?id=" + this.form2.id
        );
      } else {
        window.open(
          "http://worldskillsmuseum.cn/#/active/gongfang-detail?id=" +
            this.form2.id
        );
      }
    },
    // 提交审核
    async checkSubmit() {
      if (this.form2.currentStatus == "2" && this.form2.isAgree == "1") {
        if (this.form2.nextEmp == null) {
          this.$alert("请选择审核人！", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          });
          return;
        }
      } else if (this.form2.currentStatus == "3" && this.form2.isAgree == "1") {
        if (this.form2.nextEmp == null) {
          this.$alert("请选择审核人！", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          });
          return;
        }
      }
      // else if((this.form2.currentStatus == '4')&&(this.form2.isAgree == '1'))
      // {
      //     if(this.form2.nextEmp == null)
      //     {
      //         this.$alert('请选择发布人！', '提示', {
      //             confirmButtonText: '确定',
      //             type: 'warning'
      //         });
      //         return;
      //     }
      // }
      else if (this.form2.currentStatus == "2" && this.form2.isAgree == "2") {
        if (this.form2.previousNode == null || this.form2.previousNode == "") {
          this.$alert("请选择回退节点！", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          });
          return;
        }
      } else if (this.form2.currentStatus == "3" && this.form2.isAgree == "2") {
        if (this.form2.previousNode == null || this.form2.previousNode == "") {
          this.$alert("请选择回退节点！", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          });
          return;
        }

        if (
          this.form2.previousNode != "1" &&
          (this.form2.nextEmp == null || this.form2.nextEmp == "")
        ) {
          this.$alert("请选择回退审核人！", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          });
          return;
        }
      } else if (this.form2.currentStatus == "4" && this.form2.isAgree == "2") {
        if (this.form2.previousNode == null || this.form2.previousNode == "") {
          this.$alert("请选择回退节点！", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          });
          return;
        }

        if (
          this.form2.previousNode != "1" &&
          (this.form2.nextEmp == null || this.form2.nextEmp == "")
        ) {
          this.$alert("请选择回退审核人！", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          });
          return;
        }
      } else if (this.form2.currentStatus == "5" && this.form2.isAgree == "2") {
        if (this.form2.previousNode == null || this.form2.previousNode == "") {
          this.$alert("请选择下架到哪个节点！", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          });
          return;
        }

        if (
          this.form2.previousNode != "1" &&
          (this.form2.nextEmp == null || this.form2.nextEmp == "")
        ) {
          this.$alert("请选择下架节点审核人！", "提示", {
            confirmButtonText: "确定",
            type: "warning",
          });
          return;
        }
      }

      let assigneeCnName = "";
      if (this.form2.nextEmp) {
        assigneeCnName = this.nextEmpList.filter(
          (item) => item.userId == this.form2.nextEmp
        )[0].userCnName;
      }

      let formData = {
        id: this.form2.id,
        isAgree: this.form2.isAgree,
        previousNode: this.form2.previousNode,
        assigneeId: this.form2.nextEmp,
        assigneeCnName: assigneeCnName,
        actionNote: this.form2.actionNote,
        currentStatus: this.form2.currentStatus,
      };

      let res = await checkSubmit(formData);
      if (res.code == 200) {
        this.$modal.msgSuccess("审核成功！");
        this.open2 = false;
        this.getPage();
      }
    },
    // 加载活动类型列表
    loadActivityMenus(parentId) {
      console.log('====加载活动类型列表，parentId:', parentId);
      // 手动设置loading
      this.$set(this, 'loading', true);
      // 调用API获取三级菜单数据
      getListByParentId(parentId).then(res => {
        console.log('API返回数据:', res);
        if (res.code === 200) {
          const menuList = [];
          
          // 检查返回的数据格式，适配rows或data
          const items = res.rows || res.data || [];
          console.log('菜单项列表:', items);
          
          // 将menuName映射为label，id映射为value
          items.forEach(item => {
            menuList.push({
              label: item.menuName,
              value: item.id
            });
          });
          
          // 保存到缓存
          this.activityMenuCache[parentId] = menuList;
          this.activityMenuList = menuList;
          
          console.log('处理后的活动类型列表:', this.activityMenuList);
        } else {
          console.error('获取活动类型列表失败:', res.msg);
        }
        
        // 手动关闭loading
        this.$set(this, 'loading', false);
      }).catch(error => {
        console.error('请求活动类型列表出错:', error);
        // 手动关闭loading
        this.$set(this, 'loading', false);
      });
    },
  },
};
</script>
